package cn.shop.dys.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.List;
import cn.shop.dys.R;
import cn.shop.dys.bean.AddressInfo;
import cn.shop.dys.bean.AllIndentItem;
import cn.shop.dys.bean.CartItem;
import cn.shop.dys.bean.DeliveryInfo;
import cn.shop.dys.bean.InvoiceInfo;
import cn.shop.dys.bean.MyCheckoutAddup;
import cn.shop.dys.bean.OrderInfo;
import cn.shop.dys.bean.PaymentInfo;
import cn.shop.dys.bean.ProductInfo;
import cn.shop.dys.bean.ProductProperty;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.dys.constant.SPConstant;
import cn.shop.dys.util.SPUtil;
import cn.shop.dys.widget.ProductListItem;
import cn.shop.lib_common.CommonUtil;
/**
 * 用户订单详情
 * 作者:孙建
 * created at 2016/4/23 18:44
 */
public class UserIndentDetailActivity extends AppCompatActivity implements View.OnClickListener {
    @ViewInject(R.id.rl_logistics_query)
    private View mLogisticsQuery;
    @ViewInject(R.id.tv_user_name)
    private TextView mTvUserName;
    @ViewInject(R.id.tv_user_phone)
    private TextView mTvUserPhone;
    @ViewInject(R.id.tv_user_receive_goods_address)
    private TextView mTvUserReceiveGoodsAddress;
    @ViewInject(R.id.tv_indent_detail_number)
    private TextView mIndentDetailNumber;
    @ViewInject(R.id.tv_deliver_goods_way)
    private TextView mTvDeliverGoodsWay;
    @ViewInject(R.id.tv_pay_way)
    private TextView mPayWay;
    @ViewInject(R.id.tv_indent_create_time)
    private TextView mTvIndentCreateTime;
    @ViewInject(R.id.tv_deliver_goods_time)
    private TextView mTvDeliverGoodsTime;
    @ViewInject(R.id.tv_is_have_bill)
    private TextView mIsHaveBill;
    @ViewInject(R.id.tv_bill_origin)
    private TextView mBillOrigin;
    @ViewInject(R.id.tv_deliver_goods_request)
    private TextView mDeliverGoodsRequest;
    /*@ViewInject(R.id.tv_prodcut_name)
    private TextView mTvProductName;
    @ViewInject(R.id.tv_prodcut_style)
    private TextView mTvProductStyle;
    @ViewInject(R.id.tv_product_count)
    private TextView mTvProductCount;*/
    @ViewInject(R.id.tv_product_count_sum)
    private TextView mTvProductCountSum;
    @ViewInject(R.id.tv_product_original_price_sum)
    private TextView mTvProductOriginalPriceSum;
    @ViewInject(R.id.tv_product_freight)
    private TextView mTvProductFreight;
    @ViewInject(R.id.tv_favorable_price)
    private TextView mTvFavorablePrice;
    @ViewInject(R.id.tv_final_price_sum)
    private TextView mTvFinalPriceSum;
    @ViewInject(R.id.btn_contact_us)
    private Button mBtnContactUs;
    @ViewInject(R.id.btn_delete_indent)
    private Button mBtnDeleteIndent;
    @ViewInject(R.id.iv_common_back)
    private ImageView mBack;
    @ViewInject(R.id.tv_common_index_titile)
    private TextView mTitle;
    @ViewInject(R.id.iv_common_settings)
    private ImageView mSettings;
    private String mOrderId;
    private HttpUtils mHttpUtils;
    private Gson mGson;
    private int mProductId;
    @ViewInject(R.id.ll_indent_detail_item_add)
    private LinearLayout mDetailItemAdd;
    private PopupWindow mPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_indent_detail);
        ViewUtils.inject(this);
        mHttpUtils = new HttpUtils();
        mGson = new Gson();
        mTitle.setText("订单详情");
        init();
    }
    private void init() {
      //  mOrderId="862938";
        Intent intent = getIntent();
        String orderId = intent.getStringExtra("orderId");
     //   Bundle indentdetail = intent.getBundleExtra("indentdetail");
      //  String orderId = indentdetail.getString("orderId");
      //  int productId = indentdetail.getInt("productId",0);
        if (TextUtils.isEmpty(orderId)) {
            finish();
        }
        this.mOrderId = orderId;
      //  this.mProductId=productId;
        initEvent();
        initIndentData();
    }

    private void initIndentData() {
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        params.addHeader("userid", SPUtil.getString(UserIndentDetailActivity.this, SPConstant.USER_INFO_USER_ID));
        params.addBodyParameter("orderId", mOrderId);
        mHttpUtils.send(HttpRequest.HttpMethod.POST, CommonConstant.HOST_ORDER_DETAIL, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if (response.equals("orderDetail")) {
                                    String orderInfoStr = jsonObject.getString("orderInfo");
                                    OrderInfo orderInfo = mGson.fromJson(orderInfoStr, OrderInfo.class);
                                    //订单编号
                                    mIndentDetailNumber.setText(orderInfo.getTime());
                                    //送货方式
                                    if (orderInfo.getFlag() == 3) {
                                        mTvDeliverGoodsWay.setText("送达状态");
                                    } else {
                                        mTvDeliverGoodsWay.setText("未送达状态");
                                    }
                                    //订单生成时间
                                    CharSequence time = DateFormat.format("yyyy-MM-dd kk:mm:ss", Long.parseLong(orderInfo.getTime()));
                                    mTvIndentCreateTime.setText(time);
                                    CharSequence deliverTime = DateFormat.format("yyyy-MM-dd kk:mm:ss", Long.parseLong(orderInfo.getTime())+100000000);
                                    mTvDeliverGoodsTime.setText(deliverTime);
                                    //支付方式
                                    String paymentInfoStr = jsonObject.getString("paymentInfo");
                                    int type = mGson.fromJson(paymentInfoStr, PaymentInfo.class).getType();
                                    if (type == 1) {
                                        mPayWay.setText("货到付款");
                                    } else if (type == 2) {
                                        mPayWay.setText("货到POS机");
                                    } else if (type == 3) {
                                        mPayWay.setText("支付宝");
                                    }
                                    //地址信息
                                    String addressInfoStr = jsonObject.getString("addressInfo");
                                    AddressInfo addressInfo = mGson.fromJson(addressInfoStr, AddressInfo.class);
                                    mTvUserName.setText(addressInfo.getName());
                                    // TODO: 2016/4/23 电话号码没有
                                    mTvUserPhone.setText("13877654433");
                                    //   mTvUserPhone.setText(addressInfo.getPhoneNumber());
                                    mTvUserReceiveGoodsAddress.setText(addressInfo.getAddressArea() + addressInfo.getAddressDetail());
                                    //发票信息
                                    String invoiceInfoStr = jsonObject.getString("invoiceInfo");
                                    InvoiceInfo invoiceInfo = mGson.fromJson(invoiceInfoStr, InvoiceInfo.class);
                                    if(invoiceInfo!=null){
                                        mIsHaveBill.setText("是");
                                        mBillOrigin.setText(invoiceInfo.getInvoiceTitle());
                                   //     mDeliverGoodsRequest.setText(invoiceInfo.getInvoiceContent());
                                    }else {
                                        mIsHaveBill.setText("否");
                                        mBillOrigin.setText("无");
                                      //  mDeliverGoodsRequest.setText("无");
                                    }
                                    //送货要求
                                    String deliveryInfoStr= jsonObject.getString("deliveryInfo");
                                    String deliveryType = mGson.fromJson(deliveryInfoStr, DeliveryInfo.class).getDeliveryType();
                                    if(!TextUtils.isEmpty(deliveryType)){
                                        if(deliveryType.equals("1")){
                                            mDeliverGoodsRequest.setText("周一至周五送货");
                                        }else if(deliveryType.equals("2")){
                                            mDeliverGoodsRequest.setText("双休日及公众假期送货");
                                        }else if(deliveryType.equals("3")){
                                            mDeliverGoodsRequest.setText("时间不限，工作日双休日及公众假期均可送货");
                                        }
                                    }else {
                                        mDeliverGoodsRequest.setText("时间不限，工作日双休日及公众假期均可送货");
                                    }
                                    //商品清单
                                    String productListStr = jsonObject.getString("productList");
                                    List<CartItem> cartItems = mGson.fromJson(productListStr, new TypeToken<List<CartItem>>() {
                                    }.getType());
                                    for (CartItem cartItem : cartItems) {
                                        ProductListItem item=new ProductListItem(UserIndentDetailActivity.this);
                                        ProductInfo productInfo = cartItem.getProductInfo();
                                        Log.d("test",productInfo.toString());
                                        item.setProductName(productInfo.getName());
                                        List<ProductProperty> productProperty = productInfo.getProductProperty();
                                        if(productProperty.size()>0){
                                            StringBuilder sb=new StringBuilder();
                                            for (ProductProperty property : productProperty) {
                                                sb.append(property.getV()+",");
                                            }
                                            sb.deleteCharAt(sb.length()-1);
                                            item.setProductStyle(sb.toString());
                                        }
                                        item.setProductCount(cartItem.getProdNum()+"");
                                        mDetailItemAdd.addView(item);
                                    }
                                    String checkoutAddupStr = jsonObject.getString("checkoutAddup");
                                    MyCheckoutAddup myCheckoutAddup = mGson.fromJson(checkoutAddupStr, MyCheckoutAddup.class);
                                    mTvProductCountSum.setText(myCheckoutAddup.getTotalCount()+" 件");
                                    //new DecimalFormat("#.00").format(myCheckoutAddup.getTotalPrice())
                                    mTvProductOriginalPriceSum.setText("￥"+new DecimalFormat("#.00").format(myCheckoutAddup.getTotalPrice()));
                                    mTvProductFreight.setText(myCheckoutAddup.getFreight()+"");
                                    mTvFavorablePrice.setText("无");
                                    mTvFinalPriceSum.setText("￥"+new DecimalFormat("#.00").format(myCheckoutAddup.getTotalPrice()));
                                } else {
                                    String error = jsonObject.getString("error");
                                    String error_code = jsonObject.getString(CommonConstant.ERROR_CODE);
                                    if (error_code.equals(CommonConstant.ERROR_CODE_NO_USERID_ON_REQUEST_HEAD)) {
                                        CommonUtil.showToast(UserIndentDetailActivity.this, error);
                                    } else if (error_code.equals(CommonConstant.ERROR_CODE_UNLOGIN)) {
                                        CommonUtil.showToast(UserIndentDetailActivity.this, error);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            CommonUtil.showToast(UserIndentDetailActivity.this, "请求失败:错误码为" + statusCode);
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(UserIndentDetailActivity.this, "网络未连接1" + msg);
                    }
                });
    }

    private void initEvent() {
        mLogisticsQuery.setOnClickListener(this);
        mBtnContactUs.setOnClickListener(this);
        mBtnDeleteIndent.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mSettings.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_logistics_query:
                Intent intent=new Intent(this,LogisticsActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_contact_us:
                break;
            case R.id.btn_delete_indent:
                cancelOrderInfo();
                break;
            case R.id.iv_common_back:
                finish();
                break;
            case R.id.iv_common_settings:
                initPopupWindow(v);
                break;
        }
    }
    private void initPopupWindow (View view){
        View pwView = View.inflate(this, R.layout.view_popupwindow, null);
        View pwTop=pwView.findViewById(R.id.ll_pw_top);
        View pwBottom=pwView.findViewById(R.id.ll_pw_bottom);
        mPopupWindow = new PopupWindow(pwView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        mPopupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
        int[] location = new int[2];
        view.getLocationInWindow(location);
        mPopupWindow.showAsDropDown(view, (int) -CommonUtil.dpToPx(this, 100), (int) -CommonUtil.dpToPx(this, 0));
        pwTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserIndentDetailActivity.this, MessageActivity.class);
                startActivity(intent);
                mPopupWindow.dismiss();
            }
        });
        pwBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserIndentDetailActivity.this, MainActivity2.class);
                startActivity(intent);
                mPopupWindow.dismiss();
            }
        });
        //  popupWindow.showAtLocation(view, Gravity.RIGHT| Gravity.TOP, location[0]+40, location[1] + 40);
    }
    private void cancelOrderInfo() {
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        params.addHeader("userid", SPUtil.getString(UserIndentDetailActivity.this, SPConstant.USER_INFO_USER_ID));
        params.addBodyParameter("orderId", mOrderId);
        mHttpUtils.send(HttpRequest.HttpMethod.POST, CommonConstant.HOST_ORDER_CANCEL, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if (response.equals("orderCancel")) {
                                    CommonUtil.showToast(UserIndentDetailActivity.this, "取消订单成功");
                                    Intent intent=new Intent();
                                    intent.putExtra("orderId",mOrderId);
                                    setResult(CommonConstant.QUERY_INDENT_RESULT_CODE,intent);
                                    finish();
                                } else {
                                    String error = jsonObject.getString("error");
                                    String error_code = jsonObject.getString(CommonConstant.ERROR_CODE);
                                    if (error_code.equals(CommonConstant.ERROR_CODE_NO_USERID_ON_REQUEST_HEAD)) {
                                        CommonUtil.showToast(UserIndentDetailActivity.this, error);
                                    } else if (error_code.equals(CommonConstant.ERROR_CODE_UNLOGIN)) {
                                        CommonUtil.showToast(UserIndentDetailActivity.this, error);
                                    }else if (error_code.equals(CommonConstant.ERROR_CODE_FAILER_CANCLE_ORDER)) {
                                        CommonUtil.showToast(UserIndentDetailActivity.this, error);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            CommonUtil.showToast(UserIndentDetailActivity.this, "请求失败:错误码为" + statusCode);
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(UserIndentDetailActivity.this, "网络未连接2" + msg);
                    }

                });
    }
}
